package com.thread.syn;

//不安全的买票
//线程不安全,存在负数和重复值
public class UnsafeBuyTickets {
    public static void main(String[] args) {
        BuyTickets station = new BuyTickets();

        new Thread(station,"A").start();
        new Thread(station,"B").start();
        new Thread(station,"C").start();
    }
}

//买票
class BuyTickets implements Runnable{
    //票
    private int tickets = 10;
    boolean flag = true;//外部停止
    @Override
    public void run() {
    //买票
        while (flag){
            buy();
        }
    }
    //synchronized 同步方法,锁的是this
    public synchronized void buy(){
        //判断是否有票
        if (tickets<=0){
            flag=false;
            return;
        }
        //模拟延时:放大问题的发生性
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"买到了倒数第"+tickets--+"张票");
    }
}